﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MyPublisher.Html2OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using System.Reflection;

namespace MyPublisher.Composition.XWord
{
    [Transform(Name = "DOTNET.Html2WordML", Provider = "DOTNET", InputType = FragmentType.HTML, OutputType = FragmentType.WordML)]
    public class Html2WordML : ITransform
    {
       public void Tranform(Fragments inputs, Fragment output)
        {
            Fragment htmlFragment = inputs.GetFragment<Fragment>(FragmentType.HTML);
            Fragment outputFragment = output;
            string htmlfile = htmlFragment.Path;
            string outputfile = outputFragment.Path;

            if (!File.Exists(htmlfile))
            {
                throw new TransformException(string.Format("Input htmlfile -{0}- is not existent.", htmlfile));
            }

            HtmlTidy.Tidy(htmlfile);

            try
            {
                using(Stream stream = GetType().Assembly.GetManifestResourceStream("MyPublisher.Composition.XWord.template.docx"))
                using (MemoryStream generatedDocument = new MemoryStream())
                {
                    IOUtility.CopyStream(stream, generatedDocument);
                    using (WordprocessingDocument package = WordprocessingDocument.Open(generatedDocument,true))
                    {
                        MainDocumentPart mainPart = package.MainDocumentPart;
                        if (mainPart == null)
                        {
                            mainPart = package.AddMainDocumentPart();
                            new Document(new Body()).Save(mainPart);
                        }

                        HtmlConverter converter = new HtmlConverter(mainPart);
                        converter.ImageProcessing = ImageProcessing.AutomaticDownload;

                        Body body = mainPart.Document.Body;

                        string html = File.ReadAllText(htmlfile);
                        var paragraphs = converter.Parse(html);
                        for (int i = 0; i < paragraphs.Count; i++)
                        {
                            OpenXmlCompositeElement paragraph = paragraphs[i];
                            body.Append(paragraph);
                        }
                        mainPart.Document.Save();
                    }

                    File.WriteAllBytes(outputfile, generatedDocument.ToArray());
                }
            }
            catch (Exception e)
            {
                throw new TransformException("Failed to transform.", e);
            }
        }
    }
}
